package com.jzqf.canvas;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.Nullable;

public class RulerView extends View {
    private int mCenterX;
    private int mCenterY;

    public RulerView(Context context) {
        super(context);
    }

    public RulerView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public RulerView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public RulerView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        mCenterX = getWidth() / 2;
        mCenterY = getHeight() / 2;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //绘制坐标轴
        drawAxis(canvas);
        //绘制刻度
        drawScale(canvas);
    }

    /**
     * 绘制坐标轴
     */
    private void drawAxis(Canvas canvas) {
        Paint paint = new Paint();
        paint.setStyle(Paint.Style.FILL);
        paint.setColor(Color.RED);
        canvas.drawLine(0, mCenterY, getWidth(), mCenterY, paint);
        paint.setColor(Color.BLUE);
        canvas.drawLine(mCenterX, 0, mCenterX, getHeight(), paint);
    }

    private void drawScale(Canvas canvas) {
        Paint paint = new Paint();
        paint.setStyle(Paint.Style.FILL);
        paint.setColor(Color.RED);
        int scaleX = 0;
        while (scaleX <= getWidth()) {
            canvas.drawLine(scaleX, mCenterY - 100, scaleX, mCenterY + 100, paint);
            canvas.drawText(String.valueOf(scaleX), scaleX, mCenterY + 20, paint);
            scaleX += 50;
        }
        int scaleY = 0;
        paint.setColor(Color.BLUE);
        while (scaleY <= getHeight()) {
            canvas.drawLine(mCenterX - 100, scaleY, mCenterX + 100, scaleY, paint);
            canvas.drawText(String.valueOf(scaleY), mCenterX, scaleY, paint);
            scaleY += 50;
        }
    }
}
